import { ref, type Ref } from "vue";

export function useTableDragger(tableElement: Ref) {
  const mouseFlag = ref(false);
  const mouseOffsetX = ref(0);
  const mouseOffsetY = ref(0);

  function mouseDownHandler(e) {
    mouseOffsetX.value = e.clientX;
    mouseOffsetY.value = e.clientY;
    mouseFlag.value = true;
  }

  function mouseUpHandler(e) {
    mouseFlag.value = false;
  }

  function mouseMoveHandler(e) {
    const scrollBar = tableElement.value.scrollBarRef;
    const scrollLeft = scrollBar.wrapRef.scrollLeft;
    const scrollTop = scrollBar.wrapRef.scrollTop;
    if (mouseFlag.value) {
      scrollBar.setScrollLeft(scrollLeft + mouseOffsetX.value - (mouseOffsetX.value = e.clientX));
      scrollBar.setScrollTop(scrollTop + mouseOffsetY.value - (mouseOffsetY.value = e.clientY));
    }
  }

  return {
    mouseDownHandler,
    mouseUpHandler,
    mouseMoveHandler
  };
}

export function useScrollBarDragger(scrollBar: Ref) {
  const mouseFlag = ref(false);
  const mouseOffsetX = ref(0);
  const mouseOffsetY = ref(0);

  function mouseDownHandler(e) {
    mouseOffsetX.value = e.clientX;
    mouseOffsetY.value = e.clientY;
    mouseFlag.value = true;
  }

  function mouseUpHandler(e) {
    mouseFlag.value = false;
  }

  function mouseMoveHandler(e) {
    const scrollLeft = scrollBar.value.wrapRef.scrollLeft;
    const scrollTop = scrollBar.value.wrapRef.scrollTop;
    if (mouseFlag.value) {
      scrollBar.value.setScrollLeft(
        scrollLeft + mouseOffsetX.value - (mouseOffsetX.value = e.clientX)
      );
      scrollBar.value.setScrollTop(
        scrollTop + mouseOffsetY.value - (mouseOffsetY.value = e.clientY)
      );
    }
  }

  return {
    mouseDownHandler,
    mouseUpHandler,
    mouseMoveHandler
  };
}
